package com.ruoyi.maode.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.maode.domain.dto.DetectionResultDTO;
import com.ruoyi.maode.domain.entity.PartMeasure;
import com.ruoyi.maode.mapper.PartMeasureMapper;
import com.ruoyi.maode.service.PartMeasureService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 零件检测接口实现类
 * @author zhangwenqiang
 */
@Service
public class PartMeasureServiceImpl extends ServiceImpl<PartMeasureMapper, PartMeasure> implements PartMeasureService {

    @Override
    public Boolean getResult(DetectionResultDTO resultDTO) {

        Boolean resultBoolean = true;

        List<String> filteredValues = resultDTO.getValue().stream()
                .filter(value -> !value.isEmpty())
                .collect(Collectors.toList());
        filteredValues.stream().forEach(t ->{
            // 正则表达式匹配非数字字符
            Pattern pattern = Pattern.compile("^(?!-?\\d+(\\.\\d+)?$).+");
            Matcher matcher = pattern.matcher(t.trim());
            if (matcher.find()){
                throw new UtilException("请输入一个数字！");
            }
        });

        // 检查是否有任何值大于max,只要有一个大于max，返回false
        Boolean isMax = filteredValues.stream()
                .filter(value -> !value.isEmpty())
                .map(value -> value.replaceAll(",+$", ""))
                .map(Double::parseDouble)
                .allMatch(value -> resultDTO.getMax().compareTo(value) >= 0);

        if (!isMax) {
            resultBoolean = false;
        }
        // 检查是否有任何值小于min,只要有一个小于min，返回false
        Boolean isMin = filteredValues.stream()
                .filter(value -> !value.isEmpty())
                .map(value -> value.replaceAll(",+$", ""))
                .map(Double::parseDouble)
                .allMatch(value -> resultDTO.getMin().compareTo(value) <= 0);
        if (!isMin) {
            resultBoolean = false;
        }

        return resultBoolean;
    }
}
